// 
import React, {createContext, useReducer, useContext } from 'react';

import Taro from '@tarojs/taro';

// const {createContext} =Taro

const UserContext = createContext();

const initialState = JSON.parse(Taro.getStorageSync('userInfo') || 'null');

const userReducer = (state, action) => {
  switch (action.type) {
    case 'UPDATE_USER_INFO':
      Taro.setStorageSync('userInfo', JSON.stringify(action.payload));
      return action.payload;
    case 'GET_USER_INFO':
      return JSON.parse(Taro.getStorageSync('userInfo') || 'null');
    case 'RELOAD':
        return JSON.parse(Taro.getStorageSync('userInfo') || 'null');
    default:
      return state;
  }
};

export const UserProvider = ({ children }) => {
  const [state, dispatch] = useReducer(userReducer, initialState);

  return (
    // react 18 需要 .Provider ，19之后就不需要了
    <UserContext.Provider value={{ userInfo: state, dispatch }}>
      {children}
    </UserContext.Provider>
  );
};


export const useUserStore = () => {
    const context = useContext(UserContext);
    if (context === undefined) {
        throw new Error('useUserStore must be used within a UserProvider');
    }
    const { userInfo, dispatch } = context

    const updateUserInfo = (info = {}) => {
        dispatch({ type: 'UPDATE_USER_INFO', payload: info });
    }

    const getUserInfo = () => {
        return userInfo
    }

    const reload = () => {
        dispatch({ type: 'RELOAD' });
    }

    return {
        userInfo,
        updateUserInfo,
        getUserInfo,
        reload
    }
};